package com.vidmt.api.modules.sys.tasks;

import java.util.Collection;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.vidmt.api.common.cache.MyCacheManager;
import com.vidmt.api.common.utils.CommUtil;
import com.vidmt.api.modules.sys.Enums.TraceReason;
import com.vidmt.api.modules.sys.entity.Location;
import com.vidmt.api.modules.sys.entity.Trace;
import com.vidmt.api.modules.sys.entity.User;
import com.vidmt.api.modules.sys.service.LocationService;
import com.vidmt.api.modules.sys.service.TraceService;
import com.vidmt.api.modules.sys.service.UserService;

/**
 * @author xingqisheng
 * @version 2015-08-14
 */
@Service
@Transactional(readOnly = false)
@Lazy(false)
public class SaveLocationTask {
	private static final Logger log = LoggerFactory.getLogger(SaveLocationTask.class);
	public static final int MIN_POINTS = 5;
	@Autowired
	private LocationService locationService;
	@Autowired
	private UserService userService;
	
	@Autowired
	private MyCacheManager myCacheManager;

	@Scheduled(fixedRate = 2 * 60 * 60 * 1000) // 每隔2小时清理一次
	// @Scheduled(fixedRate = 30 * 1000) // 每隔30s清理一次
	public void saveCachedLocation() {
		log.debug("===开始清理缓存:" + CommUtil.fmtDate(new Date()));
		saveLocation();
		saveTrace();
		log.debug("===结束清理缓存:" + CommUtil.fmtDate(new Date()));
	}

	// @CacheEvict(value = "locCache", allEntries = true)
	private void saveLocation() {
		@SuppressWarnings("deprecation")
		Collection<Location> loclist = myCacheManager.getAll("locCache");
		for (Location loc : loclist) {
			User user = userService.load(loc.getUid());
			locationService.saveOrUpdate(loc, user);
		}
	}

	private void saveTrace() {
		Collection<Trace> traceList = myCacheManager.getAll("traceCache");
		for (Trace trace : traceList) {
			synchronized (trace) {
				if (trace.getPoints().size() > MIN_POINTS) {
					TraceService traceSvc = SpringContextHolder.getBean(TraceService.class);
					try {
						trace.setReason(TraceReason.TIMEEND);
						traceSvc.save(trace);
						log.debug("保存过期足迹:" + trace);
					} catch (DuplicateKeyException e) {
						log.warn("保存足迹重复：" + trace.getUid() + trace.getHash());
					}
				}
			}
		}
	}
}